package com.animee.jiujiangdict;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.animee.jiujiangdict.bean.TuWenBean;
import com.animee.jiujiangdict.utils.FileUtil;
import com.animee.jiujiangdict.utils.PatternUtils;
import com.animee.jiujiangdict.utils.RecognizeService;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    EditText mainEt;
    TextView pyTv,bsTv,cyTv,twTv;
    private Animation animation;
    private boolean hasGotToken = false;

    private AlertDialog.Builder alertDialog;
    private static final int REQUEST_CODE_GENERAL_BASIC = 106;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainEt = findViewById(R.id.main_et);
        pyTv = findViewById(R.id.main_tv_pinyin);
        bsTv = findViewById(R.id.main_tv_bushou);
        cyTv = findViewById(R.id.main_tv_chengyu);
        twTv = findViewById(R.id.main_tv_tuwen);
        alertDialog = new AlertDialog.Builder(this);
        // 将写在res/anim文件夹下的动画文件转换成对象
        animation = AnimationUtils.loadAnimation(this, R.anim.main_tv_tranlate);
        // 请选择您的初始化方式
        // initAccessToken();
        initAccessTokenWithAkSk();
    }
    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }


    /**
     * 以license文件方式初始化
     */
    private void initAccessToken() {
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("licence方式获取token失败", error.getMessage());
            }
        }, getApplicationContext());
    }

    /**
     * 用明文ak，sk初始化
     */
    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(),  "aI185YjRxKIrhRhbD97dG6Eo", "z0kcE6ng91P7qhKXfk35fn6LV3e5VTnV");
    }
    private void infoPopText(final String result) {
        alertText("", result);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initAccessToken();
        } else {
            Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE",
                    Toast.LENGTH_LONG).show();
        }
    }
    /*
    * 点击事件的监听
    * */
    public void onClick(View view){
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.main_tv_pinyin:
                pyTv.startAnimation(animation);  // 开启动画
                intent.setClass(this,SearchPinyinActivity.class);
                startActivity(intent);

                break;
            case R.id.main_tv_bushou:
                bsTv.startAnimation(animation);  //开启动画
                intent.setClass(this,SearchBuShouActivity.class);
                startActivity(intent);
                break;
            case R.id.main_tv_chengyu:
                cyTv.startAnimation(animation);
                intent.setClass(this,SearchChengyuActivity.class);
                startActivity(intent);
                break;
            case R.id.main_tv_tuwen:
                twTv.startAnimation(animation);
                if (!checkTokenStatus()) {
                    return;
                }
                intent.setClass(MainActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_GENERAL);
                startActivityForResult(intent, REQUEST_CODE_GENERAL_BASIC);
                break;
            case R.id.main_iv_setting:
                intent.setClass(this,SettingActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right,0);
                break;
            case R.id.main_iv_search:
                String text = mainEt.getText().toString();
                if (!TextUtils.isEmpty(text)) {
                    intent.setClass(this,WordInfoActivity.class);
                    intent.putExtra("zi",text);
                    startActivity(intent);
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
// 识别成功回调，通用文字识别
        if (requestCode == REQUEST_CODE_GENERAL_BASIC && resultCode == Activity.RESULT_OK) {
            RecognizeService.recGeneralBasic(this, FileUtil.getSaveFile(getApplicationContext())
                            .getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
//                            infoPopText(result);
                            TuWenBean wenBean = new Gson().fromJson(result, TuWenBean.class);
                            List<TuWenBean.WordsResultBean> wordlist = wenBean.getWords_result();
                            ArrayList<String>list = new ArrayList<>();  // 传递给下一级页面的集合
                            if (wordlist!=null&&wordlist.size()!=0) {
                                for (int i = 0; i < wordlist.size(); i++) {
                                    TuWenBean.WordsResultBean bean = wordlist.get(i);//获取每一个字符串
                                    String words = bean.getWords();
                                    String res = PatternUtils.removeAll(words);  //去掉字符串当中的标点符号，字母和数字
                                    for (int j = 0; j < res.length(); j++) {
                                        String s = String.valueOf(res.charAt(j));
                                        if (!list.contains(s)) {
                                            list.add(s);
                                        }
                                    }
                                }
                            }

                            if (list.size()==0) {
                                Toast.makeText(MainActivity.this,"无法识别图片中文字",Toast.LENGTH_SHORT).show();
                            }else{
                                Intent it = new Intent(MainActivity.this, IdentifyImgActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putStringArrayList("wordlist",list);
                                it.putExtras(bundle);
                                startActivity(it);
                            }

                        }
                    });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放内存资源
        OCR.getInstance(this).release();
    }
}
